PLUGIN_NAME = "Ami (COV)"
PLUGIN_AUTHOR = "SuperSaltyGamer"
PLUGIN_DESCRIPTION = "Search covers from MH Covers by files or albums."
PLUGIN_VERSION = "1.0.0"
PLUGIN_API_VERSIONS = ["2.10"]
PLUGIN_LICENSE = "AGPL-3.0"

from typing import List, Union
from picard.album import Album
from picard.config import TextOption, config
from picard.file import File
from picard.track import Track
from picard.coverart.image import CoverArtImage
from picard.ui.itemviews import BaseAction, register_file_action, register_album_action
from picard.ui.options import OptionsPage, register_options_page
from PyQt5 import QtCore, QtWidgets

from .client import Client
from .utils import get_available_browsers

OPTION_HOST = "cov_host"
OPTION_QUERY = "cov_query"
OPTION_BROWSER = "cov_browser"


class SearchCoverAction(BaseAction):
	NAME = "Search COV for &covers…"

	def callback(self, items: List[Union[File, Track, Album]]):
		item = items[-1] if items else None
		if isinstance(item, File) or isinstance(item, Track) or isinstance(item, Album):
			port = Client.find_available_port(10000, 12000)
			client = Client(config.setting[OPTION_HOST], port, item, self.pick_cover)
			client.start(config.setting[OPTION_BROWSER], config.setting[OPTION_QUERY])

	def pick_cover(self, item: Union[File, Track, Album], cover: CoverArtImage):
		items = [item]
		if isinstance(item, Track):
			items.extend(item.files)
		if isinstance(item, Album):
			items.extend(item.tracks)
			for track in item.tracks:
				items.extend(track.files)
		for item in items:
			for image in item.metadata.images:
				if "front" in image.types:
					item.metadata.images.remove(image)
			item.metadata.images.append(cover)
			item.update()
			item.metadata_images_changed.emit()


class PluginOptionsPage(OptionsPage):
	NAME = "ami_cov"
	TITLE = "Ami (COV)"
	PARENT = "plugins"

	options = [
		TextOption("setting", OPTION_HOST, "https://covers.musichoarders.xyz"),
		TextOption("setting", OPTION_QUERY, ""),
		TextOption("setting", OPTION_BROWSER, "Default")
	]

	def __init__(self, parent=None):
		super(PluginOptionsPage, self).__init__(parent)
		self.ui = Ui_PluginOptionsPage(self)

	def load(self):
		self.ui.host_edit.setText(self.config.setting[OPTION_HOST])
		self.ui.query_edit.setText(self.config.setting[OPTION_QUERY])
		browsers = get_available_browsers().keys()
		for browser in browsers:
			self.ui.browser_combo.addItem(browser)
		browser = self.config.setting[OPTION_BROWSER]
		browser = browser if browser in browsers else "Default"
		self.ui.browser_combo.setCurrentText(browser)

	def save(self):
		self.config.setting[OPTION_HOST] = self.ui.host_edit.text()
		self.config.setting[OPTION_QUERY] = self.ui.query_edit.text()
		self.config.setting[OPTION_BROWSER] = self.ui.browser_combo.currentText()


class Ui_PluginOptionsPage(object):

	def __init__(self, page: PluginOptionsPage):
		page.setObjectName("plugin_options_page")
		self.vertical_layout = QtWidgets.QVBoxLayout(page)
		self.vertical_layout.setObjectName("vertical_layout")
		self.host_label = QtWidgets.QLabel(page)
		self.host_label.setObjectName("host_label")
		self.host_label.setText("Website address:")
		self.vertical_layout.addWidget(self.host_label)
		self.host_edit = QtWidgets.QLineEdit(page)
		self.host_edit.setObjectName("host_edit")
		self.vertical_layout.addWidget(self.host_edit)
		self.query_label = QtWidgets.QLabel(page)
		self.query_label.setObjectName("query_label")
		self.query_label.setText("Query override:")
		self.vertical_layout.addWidget(self.query_label)
		self.query_edit = QtWidgets.QLineEdit(page)
		self.query_edit.setObjectName("query_edit")
		self.vertical_layout.addWidget(self.query_edit)
		self.browser_label = QtWidgets.QLabel(page)
		self.browser_label.setObjectName("browser_label")
		self.browser_label.setText("Browser:")
		self.vertical_layout.addWidget(self.browser_label)
		self.browser_combo = QtWidgets.QComboBox(page)
		self.browser_combo.setObjectName("browser_combo")
		self.vertical_layout.addWidget(self.browser_combo)
		self.spacer = QtWidgets.QSpacerItem(1, 1, QtWidgets.QSizePolicy.Policy.Minimum, QtWidgets.QSizePolicy.Policy.Expanding)
		self.vertical_layout.addItem(self.spacer)
		QtCore.QMetaObject.connectSlotsByName(page)


register_file_action(SearchCoverAction())
register_album_action(SearchCoverAction())
register_options_page(PluginOptionsPage)
